<?php
function add_new_teacher_msg($conn,$title,$content,$fors,$tos){
    $time = date('Y-m-d H:i:s');
    $query = "insert into exam_msg(title,content,fors,tos,time) values (?,?,?,?,?)";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("sssss", $title, $content, $fors, $tos, $time); 
    if($stmt->execute()){
        return true;
    } else {
        return false;
    }
}
$forid = $_GET['forid'];
$usernames = $_GET['usernames'];
$userid = $_GET['userid'];
if($forid == null or $userid == null){
    echo json_encode("error");
    die;
}
require('../../../cofd/functions.php');
require('../../../cofd/common.php');
$forid = encrypt($forid,'D','teache_byhbindkey721');
$mysqli = $conn;
$query = "SELECT bindteacher FROM exam_student WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $userid);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$bindteacher = $row['bindteacher'];
$teachers = array_filter(array_map('trim', explode(',', $bindteacher)));
$key = array_search($forid, $teachers);
$key = array_search($forid, $teachers);
    array_splice($teachers, $key, 1);
$newsplit = implode(',', $teachers);
if (strpos($newsplit, ',') === 0) {
    $newsplit = substr($newsplit, 1);
}
if (substr($newsplit, -1) === ',') {
    $newsplit = substr($newsplit, 0, -1);
}
$query = "UPDATE exam_student SET bindteacher = ? WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $newsplit, $userid);
if($stmt->execute()){
    $titelsc = '学生'.$usernames.'已取消跟您的绑定';
    add_new_teacher_msg($conn,$titelsc,$titelsc,$forid,'t');
    echo json_encode(array("status" => 200));
}else{
    echo json_encode(array("status" => 300));
}
$stmt->close();
$conn->close();
